function getSiteCfg() { 
    $.getJSON(
        "/api/tmpo/config_public/",
        function(json) {
            var val = 'POC: <a class="POCemail" href="mailto:' +
                      json.tmpo_poc_email + '">' + json.tmpo_poc_name +
                      '</a> Phone: (' + json.tmpo_poc_phone.substr(0,3) +
                      ') ' + json.tmpo_poc_phone.substr(3,3) + '-' + 
                      json.tmpo_poc_phone.substr(6,4);
            $("span.POCemail").append(val); 
        }
    );
}


function getDrivers() {
    $.ajax({
        type: 'GET',
        url: '/api/tmpo/drivers/',
        dataType: "json",
        success: function(json) {
            var val = $.qs('date') ? $.qs('date') : '';
            getDate(val, json['drivers']);
        },
        error: function() {
            window.location.href = "/tmpo/";
        }
    });
}


function getDate(val, drivers) {
    var url = '/api/dates/';
    url += val ? val + '/' : '';
    $.getJSON(
        url,
        function(json) {
            getWeek(json['info'][0]['today'], drivers);
        }
    );
}


function getWeek(val, drivers) {
    $.getJSON(
        '/api/dates/week/' + val + '/',
        function(json) {
            $("#driverScheduleTable, #legend").remove();
            $("div.mainContent")
                .append(proto_html['schedule'])
                .append(proto_html['legend']);
            var i = json['info'][0];
            var w = json['weekspan'][0];
            var val = '&nbsp;' + w['first'] + '&nbsp;-&nbsp;' +
                      w['seventh'] + '&nbsp;';
            $("#driverScheduleTable caption span.captionDate a:first")
                .after(val);
            var week_days = [ w['first_day'],w['second_day'],w['third_day'],
                              w['fourth_day'],w['fifth_day'],w['sixth_day'],
                              w['seventh_day'] ];
            var week_disp = [ w['first'],w['second'],w['third'],
                              w['fourth'],w['fifth'],w['sixth'],
                              w['seventh'] ];
            var week_dates = [ w['comp_first'],w['comp_second'],
                               w['comp_third'],w['comp_fourth'],
                               w['comp_fifth'],w['comp_sixth'],
                               w['comp_seventh'] ];
            $.each([0,1,2,3,4,5,6], function() {
                $("#driverScheduleTable thead tr th:eq(" + (this + 1) + ")")
                    .html( week_days[this] + '<br />' + week_disp[this] );
            });
            $.each(drivers, function() {
                var driver = this;
                $("#driverScheduleTable").append(proto_html['driver']);
                $("#driverScheduleTable tbody:last")
                    .find("tr")
                    .attr("driver_id",driver['id'])
                    .end()
                    .find("td:eq(0)")
                    .append(driver['name'])
                    .end()
                    .find("td:eq(0) span.hoverButton")
                    .click( function() {
                        window.location.href = "/tmpo/drivers/detail/?id=" + driver['id'];
                        return false;
                    })
                    .end()
                    .hover(
                        function() {
                            $(this).addClass('highlight');
                        },
                        function() {
                            $(this).removeClass('highlight');
                        }
                    )
                    ;
                $.each([0,1,2,3,4,5,6], function() {
                    var sel = "#driverScheduleTable tbody:last tr " +
                              "td:eq(" + (this + 1) + ")";
                    $(sel).attr("date",week_dates[this]);
                });
            });
            getDriverSchedule( week_dates,
                               i['previous_week'], i['next_week'],
                               drivers );
        }
    );
}


function getDriverSchedule(dates, previous, next, drivers) {
    $.each(dates, function(i, v) {
        var col = i + 1;
        var date = v;
        $.getJSON(
            '/api/tmpo/drivers/schedule/' + date + '/',
            function(json) {
                $.each(json, function() {
                    var sel = "#driverScheduleTable tr[driver_id='" +
                              this['driver_id'] + "'] " + "td:eq(" + col + ")";
                    var val = '<div style="margin-bottom:1px;" class="';
                    val += ( this['type'] == 'commitment' )
                           ? 'dsOfficeColor'
                           : 'dsUnavailableColor';
                    val += '">' + this['description'] + '</div>';
                    $(sel).append(val);
		});
            }
        );
    });
    $("#button_previous").click( function() {
        getWeek(previous, drivers);
        return false;
    });
    $("#button_next").click( function() {
        getWeek(next, drivers);
        return false;
    });
    $("#button_print").click( function() {
        makePrinter("#driverScheduleTable")();
        return false;
    }); 
}


function setProtoHTML() {    
    var proto_pre = {
        'schedule':'protoDriverScheduleTableHTML',
        'driver':'protoDriverRowHTML',
        'no_driver':'protoNoDriverRowHTML',
        'legend':'protoLegendHTML'
    };
    proto_html = {};
    $.each(proto_pre, function(i, v) {
        proto_html[i] = $("#" + v).html();
        $("#" + v).remove();
    });
}


jQuery(function($) {
    getSiteCfg();
    setProtoHTML();
    getDrivers();
    $(":radio, :checkbox").css("border", "none");
    $("#logoutNavButton").click( function() {
        $.post("/api/logout/", {},
            function() {
                window.location.href = "/tmpo/";   
            }
        );
    });
    if ($.cookie("tmpoHome")) {
        $("img.headerLogo").parent().attr('href', $.cookie("tmpoHome"));
    }
});